//
//  HWPromoteSearchController.swift
//  HWPromoteProjectAPP
//
//  Created by 王昌健 on 2022/1/28.
//  Copyright © 2022 王昌健. All rights reserved.
//

import UIKit

class HWPromoteSearchController: HWBaseViewController {
    var searchBgView:UIView!
    var searchLogoImage:UIImageView!
    var searchField:UITextField!
    var cancelButton:UIButton!
    
    var tableView:UITableView!
    var tableViewProtocol = HWPromoteSearchProtocol()
    var httpManager = HWHttpManager()
    var keyword = ""
    var type = ""
    var modelArr = NSMutableArray()
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        loadData()
        
        addRefresh()
        
        addAction()
        
    }
}

extension HWPromoteSearchController {
    private func initUI() -> Void {
        navigationView.backgroundColor = .white
        navigationView.isHidden = false
        navigationView.titleLabel.isHidden = true
        navigationView.backButton.isHidden = true
        
        view.backgroundColor = .colorWithHexString(hexString: "#F5F5F5")
        
        searchBgView = UIView()
        searchBgView.backgroundColor = .white
        searchBgView.layer.cornerRadius = 12*widthScale
        searchBgView.layer.borderWidth = 1*widthScale
        searchBgView.layer.borderColor = UIColor.colorWithHexString(hexString: "#CCCCCC").cgColor
        navigationView.addSubview(searchBgView)
        
        searchLogoImage = UIImageView()
        searchLogoImage.image = UIImage(named: "search")
        searchBgView.addSubview(searchLogoImage)
        
        searchField = UITextField.init()
        searchField.textColor = UIColor.colorWithHexString(hexString: "#333333")
        searchField.font = UIFont.systemFont(ofSize: 14*widthScale)
        searchField.delegate = self
        searchField.returnKeyType = .search
        searchBgView.addSubview(searchField)
        
        let placeHoldLabel = UILabel.init()
        placeHoldLabel.text = "搜索游戏"
        placeHoldLabel.textColor = UIColor.colorWithHexString(hexString: "#AAAAAA")
        placeHoldLabel.font = UIFont.systemFont(ofSize: 14*widthScale)
        searchField.setValue(placeHoldLabel, forKey: "_placeholderLabel")
        searchField.addTarget(self, action: #selector(searchTextFieldChange(_:)), for: .editingChanged)
        
        cancelButton = UIButton(type: .custom)
        cancelButton.setTitle("取消", for: .normal)
        cancelButton.setTitleColor(.colorWithHexString(hexString: "#333333"), for: .normal)
        cancelButton.titleLabel?.font = .systemFont(ofSize: 14*widthScale)
        cancelButton.addTarget(self, action: #selector(cancelButtonClick(_:)), for: .touchUpInside)
        navigationView.addSubview(cancelButton)
        
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .colorWithHexString(hexString: "#F5F5F5")
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        view.addSubview(tableView)
        let header = UIView()
        header.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 10)
        tableView.tableHeaderView = header
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        tableView.ly_emptyView.contentViewOffset = -40
        
        view.bringSubviewToFront(navigationView)
    }
    
    private func initFrame() -> Void {
        searchBgView.snp.makeConstraints { make in
            make.left.equalTo(20*widthScale)
            make.right.equalTo(cancelButton.snp.left).offset(-10*widthScale)
            make.bottom.equalTo(-5*widthScale)
            make.height.equalTo(36*widthScale)
        }
        
        searchLogoImage.snp.makeConstraints { make in
            make.left.equalTo(10*widthScale)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(16*widthScale)
        }
        
        searchField.snp.makeConstraints { make in
            make.left.equalTo(searchLogoImage.snp.right).offset(2*widthScale)
            make.centerY.equalToSuperview()
            make.right.equalTo(-10*widthScale)
        }
        
        cancelButton.snp.makeConstraints { make in
            make.right.equalTo(-20*widthScale)
            make.centerY.equalTo(searchBgView)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(navigationView.snp.bottom)
        }
    }
}

extension HWPromoteSearchController:UITextFieldDelegate {
    @objc func searchTextFieldChange(_ textField:UITextField) ->Void {
        if textField.text?.count == 0 {
//            self.searchTextClear!(true)
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//        self.searchText!(textField.text ?? "")
        self.keyword = textField.text ?? ""
        loadData()
        textField.endEditing(true)
        
        return true
    }
    
    @objc func cancelButtonClick(_ button:UIButton) -> Void {
        self.navigationController?.popViewController(animated: true)
    }
    
    func addAction() -> Void {
        tableViewProtocol.didClickGame = {
            mod in
            let detail = HWGameDetailsViewController()
            detail.idStr = mod.gid
            self.navigationController?.pushViewController(detail, animated: true)
        }
    }
}

extension HWPromoteSearchController {
    func loadData() -> Void {
        tableView.mj_footer?.isHidden = true
        httpManager.getPromoteGamesInfo(keyword: keyword,type: type) { models in
            self.tableViewProtocol.models = models
            self.tableView.reloadData()

            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.tableView.mj_footer?.isHidden = false
                self.modelArr.removeAllObjects()
                self.modelArr.addObjects(from: models)
            }
            self.tableViewProtocol.models = self.modelArr as? [HWPromoteGameModel]
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_footer?.isHidden = true
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
    
    func addRefresh() -> () {
        
//        tableView.mj_header = MJRefreshNormalHeader()
//        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
        tableView.mj_footer?.isHidden = true
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        self.tableView.mj_footer?.endRefreshing()
        self.httpManager.getPromoteGamesInfoFooter(keyword: keyword,type: type) { models in
            self.tableView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.modelArr.addObjects(from: models)
            }
            self.tableViewProtocol.models = self.modelArr as? [HWPromoteGameModel]
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
}
